<?php

namespace app\controller;

use app\BaseController;
use app\lib\exception\ParamException;
use app\model\ValidatePriceRecord;
use app\services\BlackService;
use app\services\OrderService;
use app\services\PassengerService;
use app\services\TicketService;
use app\utils\AliyunUtils;
use app\validate\CityValidate;
use app\validate\FileValidate;
use app\validate\OrderValidate;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;


class OrderController extends BaseController
{
    /**
     * @var PassengerService
     */
    private $passengerService;
    /**
     * @var BlackService
     */
    private $blackService;
    /**
     * @var OrderService
     */
    private $service;
    /**
     * @var TicketService
     */
    private $ticketService;
    /**
     * @var \think\cache\Driver
     */
    private $redis;

    public function __construct(App $app)
    {
        $this->passengerService = new PassengerService();
        $this->ticketService = new TicketService();
        $this->redis =  Cache::store('redis');
        $this->service = new OrderService();
        parent::__construct($app);
    }

    public function getFrequently()
    {

        return $this->returnJson($this->passengerService->getList($this->request->get('keyword')));
    }

    //'P'=>'护照',
    //            'IP'=>'电子护照',
    //            'M'=>'军方证件',
    //            'G'=>'商船船员证',
    //            'A'=>'港澳居民来往内地通行证、台湾居民来往大陆通行证',
    //            'C'=>'外交部签发的驻华外交人员证',
    //            'I'=>'十六周罗以下所持户口本、学生证、户口所在地公安机关出具的身份证明',
    //            'F'=>'非标证件[名国或地区颁发]',
    //            'IN 芳邻卡'=>'美加'
    public function IdentificationDocument()
    {
        $type = $this->request->param('type');
        $card = $this->request->file('card');
        validate(FileValidate::class)
            ->scene('image')
            ->check(['image' => $card]);

        $aliyunUtils = new AliyunUtils();

        switch ($type) {

            case 'A':
                $IDCard = $aliyunUtils->getExitEntry($card);
                break;

                case 'P3':
                $IDCard = $aliyunUtils->getPermitToHK($card);
                break;
            //中国护照
            case 'P1':
                $IDCard = $aliyunUtils->getPASSPORT1($card);
                break;
            case 'P2':
                $IDCard = $aliyunUtils->getPASSPORT2($card);
                break;
            //身份证
            case 'NI':
                $IDCard = $aliyunUtils->getIDCard($card);
                break;
        }

        return $this->returnJson($IDCard);
    }



    public function validatePrice(){$this->blackService = new BlackService($this->request->bcw??['data'=>[]]);
        $param = $this->request->param();
//        $work_no, $price, $seat, $flight_no, $voyage, $fly_day, $fly_time, $fly_time, $chd_seat, $chd_number
        $flightSeatPriceList = $this->blackService->queryFlightSeatPrice( strtotime($param['fly_day']), $param['fly_time'], $param['voyage'], $param['flight_no'], [$param['seat']],$param['work_no']);

        if ($param['seat'] == $param['chd_seat'] )$param['people_number']+=$param['chd_number'];


        $result = [
            'price'=>null,
            'no'=>null,
            'pass'=>false,
            'remark' => null
        ];

        foreach($flightSeatPriceList[$param['seat']] as $flightSeatPrice){



            if ($flightSeatPrice['no'] ==  $param['no'] ){
                $result['no'] = $param['no'];
                if ($flightSeatPrice['CNY'] ==  $param['price']) {
                    if ($flightSeatPrice['number'] != 'A') {
                        if ($flightSeatPrice['number'] == 'L' || $flightSeatPrice['number'] == 'Q' || $flightSeatPrice['number'] == 'S' ){
                            $result['remark'] = $param['seat']."仓无位";
                            break;
                        }

                        if ((int)$flightSeatPrice['number']< $param['people_number'] ){
                            $result['remark'] = $param['seat']."仓位不够，请分离下单";
                            break;
                        }

                    }

                    $result['pass'] = true;
                    break;
                }

                $result['price'] = $flightSeatPrice['CNY'];
                $result['remark'] = "变价:".$flightSeatPrice['CNY'];
                break;
            }
            $result['remark'] = "没有".$param['no']."的价格";
        }


        $validatePriceRecord = new ValidatePriceRecord();
        $param['result_price'] = $result['price'];
        $param['result_remark'] = $result['remark'];
        $param['result_pass'] = (string)$result['pass'];
        $validatePriceRecord->save($param);

        return $this->returnJson($result);
    }


    //'passenger'=>[
    //`name` varchar(50) DEFAULT NULL COMMENT '名字',
    //`second_name` varchar(50) DEFAULT NULL COMMENT '第二名字',
    //`id_card` varchar(50) DEFAULT NULL COMMENT '身份证',
    //`is_chd` int(1) DEFAULT NULL COMMENT '儿童',
    //`birthday` int(11) DEFAULT NULL COMMENT '生日',
    //`nationality` varchar(10) DEFAULT NULL COMMENT '国籍',
    //`card_type` varchar(3) DEFAULT NULL COMMENT '身份证类型',
    //`card_expiration` varchar(11) DEFAULT NULL COMMENT '证件有效期 Y-m-d',
    //`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
    //`sex` int(1) DEFAULT NULL COMMENT '性别',
    //`country_code` varchar(10) DEFAULT NULL COMMENT '发证国家',
    //`is_frequently` varchar(255) DEFAULT NULL COMMENT '是否常用',
    //'inft'=>[
    //  'name'=>'',
    //  'birthday' =>
    //  ]
    //]

    //'flight' =>[
    // "office_no" : "ZUH140" ,
    //    "flight_no" :"SC1160",
    //     "sales_id" :1,
    //    "patron_id" :"3199637",
    //    "fly_day" :"2024-05-01",
    //    "fly_time" :"12:10",
    //    "sales_price" :""
    //]
    public function add()
    {

        $param = $this->request->param();
        validate(OrderValidate::class)
            ->scene('flight')
            ->check($param['flight']);

        $result = [];
        Db::startTrans();
        try {
            $result['order'] = $this->service->add($this->request->user->id, $param['flight']['sales_type'], $param['flight']['currency'], $param['flight']['origin'], $param['flight']['destination'], $param['flight']['remark'], $param['flight']['seat_type'], $param['flight']['flight_no'], $param['flight']['fly_day'], $param['flight']['fly_time'], $param['flight']['sales_price'], $param['flight']['office_no']);

            $result['passengerList'] = $this->passengerService->add($param['passenger'], $param['flight']['fly_day']);


            $result['ticket'] = $this->ticketService->add($result['passengerList'], $result['order']['id'], $param['seat']);
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();

            throw new ParamException($exception->getMessage()."\n".$exception->getTraceAsString());
        }

        $token = 'cod_order'.bin2hex(random_bytes(16));

        $this->redis->set($token, json_encode($result));

        return $this->returnJson($token);
    }


    public function booking(){
        $this->service = new BlackService($this->request->bcw ??['data'=>[]]);
        $token = $this->request->param('token');
        $out_who = $this->request->param('out_who', 'adu');
        $big_pnr = $this->request->param('big_pnr', '');

        $out_who == '' && $out_who = 'adu';
        $param = $this->redis->get($token);

        if (empty($param)){
            throw new ParamException('密钥错误或不存在');
        }else{
            $param = json_decode($param, true);
        }



        $result = $this->service->booking($param['order'], $param['passengerList'], $param['ticket'], $out_who, $big_pnr);
        if ($result['adu_pnr'] == null && $result['chd_pnr']['error'] == null) {
            $this->redis->delete($token);
        }


        if ($out_who == 'adu' && $result['chd_pnr'] == null) {
            $this->redis->delete($token);
        }




        return $this->returnJson($result);
    }


    public function getList(){
        $page = $this->request->param('page', 1);
        $size = $this->request->param('size', 50);
        $order_number = $this->request->param('order_number', '');
        $user_id = $this->request->param('user_id', '');
        $tm = $this->request->param('tm', '');
        $flight_no = $this->request->param('flight_no', '');
        $pnr = $this->request->param('pnr', '');
        $booking_day_start = $this->request->param('booking_day_start', '');
        $booking_day_end = $this->request->param('booking_day_end', '');
        $status = $this->request->param('status', '');
        $fly_day_start = $this->request->param('fly_day_start', '');
        $fly_day_end = $this->request->param('fly_day_end', '');


        $list = $this->service->getList($size, $page, $order_number, $user_id, $tm, $flight_no, $pnr, $booking_day_start, $booking_day_end, $status, $fly_day_start, $fly_day_end);


        return $this->returnJson($list);




    }
}